﻿using MxWeiXinPF.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Web.admin.sms;

namespace MxWeiXinPF.Web.admin.users
{
    public partial class SendMessageCheck : MxWeiXinPF.Web.UI.ManagePage
    {
        protected string action = MXEnums.ActionEnum.Add.ToString();
        protected MxWeiXinPF.Model.manager admin_info;
        private int id = 0;
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        public static string Pwd = ConfigurationManager.AppSettings["WebReference.Service.Pwd"];
        protected int totalCount;
        public static string UserName = ConfigurationManager.AppSettings["WebReference.Service.UserName"];
        protected int wid = 0;

        protected void btnAddQuery_Click(object sender, EventArgs e)
        {
            string str = this.tbTxt.Text.Trim();
            if (string.IsNullOrEmpty(str))
            {
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, base.GetType(), null, "alert('条件的值不能为空！');", true);
            }
            else
            {
                string selectedValue = this.ddlContent.SelectedValue;
                string text = this.ddlContent.SelectedItem.Text;
                string str4 = this.ddlQuery.SelectedValue;
                string str5 = this.ddlQuery.SelectedItem.Text;
                if (str4.Equals("like"))
                {
                    this.hQuery.Value = " and " + selectedValue + " " + str4 + " '%" + str + "%' ";
                    this.lbQuery.Text = " 并且 " + text + "  " + str5 + " '" + str + "' ";
                }
                else
                {
                    if (selectedValue.Equals("sex"))
                    {
                        if (str.Equals("男"))
                        {
                            str = "1";
                        }
                        else
                        {
                            str = "0";
                        }
                    }
                    string str6 = this.hQuery.Value;
                    this.hQuery.Value = str6 + " and " + selectedValue + " " + str4 + " " + str + " ";
                    str6 = this.lbQuery.Text;
                    this.lbQuery.Text = str6 + " 并且 " + text + " " + str5 + " '" + str + "' ";
                }
                this.UpdatePanel2.Update();
            }
        }

        protected void btnDel_Click(object sender, EventArgs e)
        {
            this.hQuery.Value = "";
            this.lbQuery.Text = "";
            this.UpdatePanel2.Update();
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            string strWhere = this.CombSqlTxt(this.wid) + this.hQuery.Value;
            DataSet listForPhone = new MxWeiXinPF.BLL.users().GetListForPhone(strWhere, out this.totalCount);
            if ((listForPhone == null) || (listForPhone.Tables[0].Rows.Count == 0))
            {
                base.JscriptMsg("没有符合条件的数据！", "back", "Error");
            }
            else
            {
                int num = 0;
                for (int i = 0; i < listForPhone.Tables[0].Rows.Count; i++)
                {
                    DataRow row = listForPhone.Tables[0].Rows[i];
                    if ((row["mobile"] != null) && (row["mobile"].ToString().Length == 11))
                    {
                        num++;
                        builder.Append(row["mobile"] + ",");
                    }
                }
                this.tbPhone.Value = builder.ToString().Substring(0, builder.Length - 1).ToString();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {

                base.ChkAdminLevel("SendMessageCheck", MXEnums.ActionEnum.Edit.ToString());
                MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
                if (this.tbMessageContent.Value.Length > 130)
                {
                    base.JscriptMsg("短信不能超过130个汉字！", "back", "Error");
                }
                else if (this.tbPhone.Value.Length > 0x1770)
                {
                    base.JscriptMsg("一次发送不能超过500个号码，请复制号码，分多次发送！", "back", "Error");
                }
                else if (this.tbPhone.Value.Equals(""))
                {
                    base.JscriptMsg("发送号码不能为空！", "back", "Error");
                }
                else
                {
                    string phone = this.tbPhone.Value.Trim().Replace("，", ",");
                    int length = this.tbPhone.Value.Trim().Split(new char[] { ',' }).Length;
                    int shopid = 0;
                    if (this.admin_info != null)
                    {
                        shopid = this.admin_info.id;
                    }
                    else
                    {
                        this.admin_info = base.GetAdminInfo();
                        shopid = this.admin_info.id;
                    }
                    int id = sendmessage.InsertSendSMSmore(phone, this.tbMessageContent.Value.Trim(), length, 0x27, shopid);
                    if (id > 0)
                    {
                        string htmlFromUrl = this.GetHtmlFromUrl(phone, this.tbMessageContent.Value.Trim());
                        BlueSmsMgr ms = new BlueSmsMgr(this.wid);
                        ms.SendSMS(phone, this.tbMessageContent.Value.Trim());
                        //if (!string.IsNullOrEmpty(htmlFromUrl) && !htmlFromUrl.Equals(""))
                        //{
                            DateTime now = DateTime.Now;
                            if (sendmessage.UpdateIsSend("1", now, id))
                            {
                                base.JscriptMsg("发送成功！", "back", "Success");
                                this.tbPhone.Value = "";
                            }
                        //}
                        //else
                        //{
                        //    base.JscriptMsg("发送失败！", "back", "Error");
                        //}
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected string CombSqlTxt(int wid)
        {
            StringBuilder builder = new StringBuilder();
            if (wid != 0)
            {
                builder.Append(" and wid=" + wid);
            }
            if (this.admin_info != null)
            {
                builder.Append(" and shopid=" + this.admin_info.id);
            }
            else
            {
                this.admin_info = base.GetAdminInfo();
                builder.Append(" and shopid=" + this.admin_info.id);
            }
            return builder.ToString();
        }

        public string GetHtmlFromUrl(string Phone, string ContentTxt)
        {
            string format = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&product=&extno=";
            byte[] bytes = new UTF8Encoding().GetBytes(string.Format(format, new object[] { UserName, Pwd, Phone, ContentTxt }));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PostUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Flush();
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return "1";
            }
            return "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                string queryString = MXRequest.GetQueryString("action");
                this.admin_info = base.GetAdminInfo();
                this.wid = admin_info.id;
                if (!string.IsNullOrEmpty(queryString) && (queryString == MXEnums.ActionEnum.Edit.ToString()))
                {
                    this.action = MXEnums.ActionEnum.Edit.ToString();
                    this.id = MXRequest.GetQueryInt("id");
                    if (this.id == 0)
                    {
                        base.JscriptMsg("传输参数不正确！", "back", "Error");
                        return;
                    }
                    if (!new MxWeiXinPF.BLL.sendmessage().Exists(this.id))
                    {
                        base.JscriptMsg("信息不存在或已被删除！", "back", "Error");
                        return;
                    }
                }
                if (!this.Page.IsPostBack)
                {
                    
                }

            }
            catch (Exception ex)
            {

            }
        }
    }
}